import React, { useState, useEffect, useCallback } from 'react';
import Prism from 'prismjs';
import 'prismjs/themes/prism.css';
import 'prismjs/components/prism-markdown';
import './EditPanel.css'; // 引入CSS文件

interface EditPanelProps {
  note: Note | null;
  onNoteEdit: (title: string, body: string) => void;
}

const EditPanel: React.FC<EditPanelProps> = ({ note, onNoteEdit }) => {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const [isMarkdown, setIsMarkdown] = useState(true);
  const [saveStatus, setSaveStatus] = useState<string | null>(null);

  useEffect(() => {
    if (note) {
      setTitle(note.title || '');
      setBody(note.body || '');
    } else {
      setTitle('');
      setBody('');
    }
  }, [note]);

  const handleSave = useCallback(() => {
    if (note) {
      setSaveStatus('保存中...');
      onNoteEdit(title, body);
      const timer = setTimeout(() => setSaveStatus(null), 2000);
      return () => clearTimeout(timer);
    }
  }, [note, title, body, onNoteEdit]);

  const getFormattedContent = useCallback((content: string) => {
    try {
      return Prism.highlight(content, Prism.languages.markdown, 'markdown');
    } catch {
      return content;
    }
  }, []);

  if (!note) {
    return <div className="notes__preview">请选择一个笔记</div>;
  }

  return (
    <div className="notes__preview">
      <div className="notes__toolbar">
        <div className="notes__toolbar-left">
          <button 
            className="notes__toolbar-button" 
            onClick={() => setIsMarkdown(!isMarkdown)}
          >
            {isMarkdown ? '预览模式 👁️' : '编辑模式 ✏️'}
          </button>
        </div>
        {saveStatus && (
          <div className="notes__toolbar-right">
            <span className="notes__save-status">
              {saveStatus === '保存中...' ? '💾' : '✓'} {saveStatus}
            </span>
          </div>
        )}
      </div>
      <input
        className="notes__title"
        type="text"
        placeholder="新笔记..."
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        onBlur={handleSave}
      />
      {isMarkdown ? (
        <textarea
          className="notes__body"
          placeholder="编辑笔记..."
          value={body}
          onChange={(e) => setBody(e.target.value)}
          onBlur={handleSave}
        />
      ) : (
        <div
          className="notes__body-preview"
          dangerouslySetInnerHTML={{ __html: getFormattedContent(body) }}
        />
      )}
    </div>
  );
};

export default React.memo(EditPanel);
